package eerbaar.v2.gamebuilder.client.request;

import eerbaar.game.IGame;
import eerbaar.message.lib.DisplayMessageMsg;
import eerbaar.message.lib.LevelChangeMsg;
import eerbaar.message.lib.ScoreChangeMsg;
import eerbaar.persona.IPersona;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.message.MsgHelper;
import eerbaar.shared.persist.ISerializerService;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.v2.app.GameHelper;
import eerbaar.v2.app.mover.IPersonaMover;
import eerbaar.v2.app.mover.PersonaMover;

public class RequestProcessor implements IRequestProcessor {

    private IGame game;
    private boolean processingNeeded;

    @Override
    public boolean needsProcessing() {
        return this.processingNeeded;
    }

    @Override
    public void processInGameLoop() {

        if (this.game == null) {
            return;
        }

        IGame old = GameHelper.getGame();
        if (old != null) {
            old.term();
        }

        this.game.init();

        IPersona pet = this.game.getPersona("pet");
        IPersonaMover mover = new PersonaMover(pet);
        ServiceFactory.register(IPersonaMover.class, mover);

        GameHelper.setGame(this.game);

        MsgHelper.sendMsg(LevelChangeMsg.class, new LevelChangeMsg());
        MsgHelper.sendMsg(ScoreChangeMsg.class, new ScoreChangeMsg());

        String goal = this.game.getLevel().getGoal();
        DisplayMessageMsg msg = new DisplayMessageMsg(goal);
        MsgHelper.sendMsg(DisplayMessageMsg.class, msg);

        this.game = null;
        this.processingNeeded = false;
    }

    @Override
    public void processInWorkerThread(String content) {

        ISerializerService service = ServiceFactory
                .getService(ISerializerService.class);
        try {
            this.game = service.load(IGame.class, content);
            this.processingNeeded = true;
        } catch (GameException e) {
            e.printStackTrace();
        }
    }

}
